/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.util;
import cn.ac.iie.di.datadock.rdata.exchange.client.exception.REConnectionException;
import cn.ac.iie.di.datadock.rdata.exchange.client.exception.RESessionException;
import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSession;
import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSessionBuilder;
import java.util.LinkedList;
import java.util.NoSuchElementException;

/**
 *
 * @author shipengfeng
 */
public class SessionPool {

    RESendSessionBuilder builder;
    LinkedList<RESendSession> pool;

    public SessionPool(RESendSessionBuilder builder) {
        this.builder = builder;
        pool = new LinkedList<>();
    }

    public synchronized RESendSession borrowSession() throws RESessionException, REConnectionException {
        try {
            return pool.removeFirst();
        } catch (NoSuchElementException ex) {
            RESendSession session = (RESendSession) builder.build();
            session.start();
            return session;
        }
    }

    public synchronized void returnSession(RESendSession session) {
        pool.add(session);
    }
}